<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\User;
use App\Models\UserRole;
use App\Models\Project;
use App\Models\Village;
use App\Models\Street;
use App\Models\Grid;
use App\Models\GridGroup;
use App\Models\AssessCompany;
use App\Models\MappingCompany;
use App\Models\DisagreeReason;
use App\Models\HouseProve;
use App\Models\Segment;
use App\Models\BuildForm;
use App\Models\Banner;
use App\Models\GridPrice;
use App\Models\ProtocolSet;
use App\Models\HouseType;
use App\Models\AssessType;
use Illuminate\Support\Facades\Auth;
use Tymon\JWTAuth\Facades\JWTAuth;
use Illuminate\Support\Facades\Validator;

// 基础数据
class BasicDataController extends Controller
{
    // 获取项目列表
    public function projectList()
    {
        $data = Project::query()
        ->select('id','name')
        ->orderBy('id')
        ->get()
        ->toArray();
        return showData($data);    
    }

    // 获取村庄列表
    public function villageList(Request $request)
    {
        $validate = Validator::make($request->all(), [
            'project_id' => 'required',
        ], [
            'project_id.required' => '请输入项目id',
        ]);

        if ($validate->fails()) {
            return showError($validate->errors()->first());
        }

        $params = $validate->getData();

        $street_id = $request->input('street_id', '');

        $data = Village::query()
        ->select('id','name')
        ->when($street_id, function ($query) use ($street_id) {
            $query->whereIn('street_id', explode(',',$street_id));
        })
        ->where('project_id',$params['project_id'])
        ->orderBy('id')
        ->get()
        ->toArray();
        return showData($data);    
    }

    // 获取街道列表
    public function streetList(Request $request)
    {
        $validate = Validator::make($request->all(), [
            'project_id' => 'required',
        ], [
            'project_id.required' => '请输入项目id',
        ]);

        if ($validate->fails()) {
            return showError($validate->errors()->first());
        }

        $params = $validate->getData();

        $data = Street::query()
        ->select('id','name')
        ->where('project_id',$params['project_id'])
        ->orderBy('id')
        ->get()
        ->toArray();
        return showData($data);    
    }

     // 获取工作身份
     public function userRoleList(Request $request)
     {
        $data = UserRole::query()
        ->select('id','name')
        ->orderBy('id')
        ->get()
        ->toArray();
        return showData($data);    
     }

    // 获取网格组
    public function gridGroupList(Request $request)
    {
        $validate = Validator::make($request->all(), [
            'project_id' => 'required',
        ], [
            'project_id.required' => '请输入项目id',
        ]);

        if ($validate->fails()) {
            return showError($validate->errors()->first());
        }

        $params = $validate->getData();

        $village_id = $request->input('village_id', '');

        $data = GridGroup::query()
        ->select('id','name')
        ->when($village_id, function ($query) use ($village_id) {
            $query->whereIn('village_id', explode(',',$village_id));
        })
        ->where('project_id',$params['project_id'])
        ->orderBy('id')
        ->get()
        ->toArray();
        return showData($data);    
    }

    // 获取轮播图
    public function bannerList(Request $request)
    {
        $validate = Validator::make($request->all(), [
            'project_id' => 'required',
        ], [
            'project_id.required' => '请输入项目id',
        ]);

        if ($validate->fails()) {
            return showError($validate->errors()->first());
        }

        $params = $validate->getData();

        $data = Banner::query()
        ->select('id','name','img_id')
        ->where('project_id',$params['project_id'])
        ->where('status',1)
        ->orderBy('id')
        ->get()
        ->toArray();

        foreach($data as &$v){
            $v['img_url']=$v['img_id']?$this->getImageUrl($v['img_id'])['remote_url']:'';
        }
        return showData($data);    
    }

    // 获取评估机构
    public function assessCompanyList(Request $request)
    {
        $validate = Validator::make($request->all(), [
            'project_id' => 'required',
        ], [
            'project_id.required' => '请输入项目id',
        ]);

        if ($validate->fails()) {
            return showError($validate->errors()->first());
        }

        $params = $validate->getData();

        $data = AssessCompany::query()
        ->select('id','name')
        ->where('project_id',$params['project_id'])
        ->orderBy('id')
        ->get()
        ->toArray();
        return showData($data);    
    }

    // 获取测绘机构
    public function mappingCompanyList(Request $request)
    {
        $validate = Validator::make($request->all(), [
            'project_id' => 'required',
        ], [
            'project_id.required' => '请输入项目id',
        ]);

        if ($validate->fails()) {
            return showError($validate->errors()->first());
        }

        $params = $validate->getData();

        $data = MappingCompany::query()
        ->select('id','name')
        ->where('project_id',$params['project_id'])
        ->orderBy('id')
        ->get()
        ->toArray();
        return showData($data);    
    }

    // 获取不同意理由
    public function disagreeReasonList(Request $request)
    {
        $validate = Validator::make($request->all(), [
            'project_id' => 'required',
        ], [
            'project_id.required' => '请输入项目id',
        ]);

        if ($validate->fails()) {
            return showError($validate->errors()->first());
        }

        $params = $validate->getData();

        $data = DisagreeReason::query()
        ->select('id','content')
        ->where('project_id',$params['project_id'])
        ->orderBy('id')
        ->get()
        ->toArray();
        return showData($data);    
    }

    // 获取房产证号
    public function houseProveList(Request $request)
    {
        $validate = Validator::make($request->all(), [
            'type' => 'required',
        ], [
            'type.required' => '请输入类型',
        ]);

        if ($validate->fails()) {
            return showError($validate->errors()->first());
        }

        $params = $validate->getData();

        $data = HouseProve::query()
        ->select('id','name')
        ->where('status',1)
        ->where('type',$params['type'])
        ->orderBy('id')
        ->get()
        ->toArray();
        return showData($data);    
    }

    // 获取号段
    public function segmentList(Request $request)
    {
        $data = Segment::query()
        ->select('id','name')
        ->orderBy('id')
        ->get()
        ->toArray();
        return showData($data);    
    }

    // 获取建筑形式
    public function buildFormList(Request $request)
    {
        $data = BuildForm::query()
        ->select('id','name')
        ->orderBy('id')
        ->get()
        ->toArray();
        return showData($data);    
    }

    // 获取户型
    public function houseTypeList(Request $request)
    {
        $validate = Validator::make($request->all(), [
            'project_id' => 'required',
        ], [
            'project_id.required' => '请输入项目id',
        ]);

        if ($validate->fails()) {
            return showError($validate->errors()->first());
        }
        $params = $validate->getData();

        $type = $request->input('type', ''); // 1实选2预选

        $data = HouseType::query()
        ->where('project_id',$params['project_id'])
        ->when($type, function ($query) use ($type) {
            $query->where('type', $type);
        })
        ->where('status',1)
        ->orderBy('id')
        ->get()
        ->toArray();

        if($data){
            foreach($data as &$v){
              $v['img_ids']=$v['img_ids']?$this->getImageUrl($v['img_ids'],1):[];
            }
        }
     
        return showData($data);  
    }

    // 获取网格
    public function gridList(Request $request)
    {
        $validate = Validator::make($request->all(), [
            'page' => 'required',
        ], [
            'page.required' => '请输入page',
        ]);

        if ($validate->fails()) {
            return showError($validate->errors()->first());
        }

        $params = $validate->getData();
      
        $type = $request->input('type', '');
        $user=auth('api')->user()??'';
       
        $data = Grid::query()
        // ->select('id','name','into_door_status','sign_status','vacate_room_status','settlement_status','bank_status','grant_status')
        ->with('villager:name,grid_id')
        ->with('approval_list:apply_status,apply_type,grid_id')
        ->where('project_id',$user->project_id??0)
        ->where('segment_id',$user->segment_id??0)
        ->whereIn('grid_group_id',explode(',',$user->grid_group_id))
        ->where('opinion','<>',2)
        ->when($request->keywords, function ($query) use ($request) {
            $query->where(function($query) use ($request){
                $query->where('name', 'like', '%' . $request->keywords . '%')
                ->orWhere(function($query) use ($request){
                    $query->whereHas('villager', function($query) use ($request){
                        $query->where('name', 'like', '%' . $request->keywords . '%');
                    });
                });
            });
           
        })
        ->when($request->grid_group_id, function ($query) use ($request) {
            $query->where('grid_group_id',$request->grid_group_id);
        })
        ->when($type, function ($query) use ($type) {
            if ($type == 1) {
                //入户-未开始
                $query->where('into_door_status', 0);
            } elseif ($type == 2) {
                //入户-进行中
                $query->where('into_door_status', 2);
            } elseif ($type == 3)  {
                //入户-已完成
                $query->where('into_door_status', 1);
            }elseif ($type == 4)  {
                //测绘-待测绘
                $query->where('mapping_company_id','<>', 0);
                $query->where('mapping_status', 0);
            }elseif ($type == 5)  {
                //测绘-已测绘
                $query->where('mapping_status', 1);
            }elseif ($type == 6)  {
                //评估-待评估
                $query->where('assess_company_id','<>', 0);
                $query->where('assess_status', 0);
            }elseif ($type == 7)  {
                //评估-已评估
                $query->where('assess_status', 1);
            }elseif ($type == 8)  {
                //户型-待选择
                $query->where('into_door_status', 1);
                $query->where('supply_form', 2);
                $query->where('house_status', 0);
                $query->whereHas('approval_list', function($query){
                    $query->whereIn('apply_type', [14,15,17,18])->where('apply_status', 1);
                });
            }elseif ($type == 9)  {
                //户型-已选择
                $query->where('house_status', 1);
            }elseif ($type == 10)  {
                //签约-待签约
                $query->where('into_door_status', 1);
                $query->where('sign_status', 0);
                $query->whereHas('approval_list', function($query){
                    $query->whereIn('apply_type', [14,15,17,18])->where('apply_status', 1);
                });
                $query->where(function($query) {
                    $query->where('dualuse_area', 0)
                    ->orWhere(function($query){
                        $query->whereHas('approval_list', function($query) {
                            $query->where('apply_type', 16)->where('apply_status', 1);
                        });
                    });
                });
            }elseif ($type == 11)  {
                //签约-待签约-审批中
                $query->where('sign_status', 2);
            }elseif ($type == 12)  {
                //签约-已签约
                $query->where('sign_status', 1);
            }elseif ($type == 13)  {
                //签约-已签约-应支付(甲付已)
                $query->where('sign_status', 1);
                $query->whereHas('grid_price', function($query){
                    $query->where('party_a_fee','>=', 0)->where('party_b_fee', 0);
                });
            }elseif ($type == 14)  {
                //签约-已签约-应缴纳(已付甲)
                $query->where('sign_status', 1);
                $query->whereHas('grid_price', function($query){
                    $query->where('party_b_fee','>', 0);
                });
            }elseif ($type == 15)  {
                //腾房-待腾房
                $query->where('sign_status', 1);
                $query->where('if_sign', 1);
                $query->where('vacate_room_status', 0);
            }elseif ($type == 16)  {
                //腾房-待腾房-审批中
                $query->where('vacate_room_status', 2);
            }elseif ($type == 17)  {
                //腾房-已腾房
                $query->where('vacate_room_status', 1);
            }elseif ($type == 18)  {
                //结算-已签约并腾房-应支付(甲付已)
                $query->where('sign_status', 1);
                $query->where('if_sign', 1);
                $query->where('vacate_room_status', 1);
                $query->whereHas('grid_price', function($query){
                    $query->where('party_a_fee','>=', 0)->where('party_b_fee', 0);
                });
            }elseif ($type == 19)  {
                //结算-已签约并腾房-应缴纳(已付甲)
                $query->where('sign_status', 1);
                $query->where('if_sign', 1);
                $query->where('vacate_room_status', 1);
                $query->whereHas('grid_price', function($query){
                    $query->where('party_b_fee','>', 0);
                });
            }elseif ($type == 20)  {
                //结算-已结算应支付(甲付已)
                $query->where('settlement_status', 1);
                $query->whereHas('grid_price', function($query){
                    $query->where('party_a_fee','>=', 0)->where('party_b_fee', 0);
                });
            }elseif ($type == 21)  {
                //结算-待结算应支付(甲付已)
                $query->where('vacate_room_status', 1);
                $query->where('settlement_status', 0);
                $query->whereHas('grid_price', function($query){
                    $query->where('party_a_fee','>=', 0)->where('party_b_fee', 0);
                });
            }elseif ($type == 22)  {
                //结算-待结算应支付(甲付已)-审批中
                $query->where('settlement_status', 2);
                $query->whereHas('grid_price', function($query){
                    $query->where('party_a_fee','>=', 0)->where('party_b_fee', 0);
                });
            }elseif ($type == 23)  {
                //结算-已结算应缴纳(已付甲)
                $query->where('settlement_status', 1);
                $query->whereHas('grid_price', function($query){
                    $query->where('party_b_fee','>', 0);
                });
            }elseif ($type == 24)  {
                //结算-待结算应缴纳(已付甲)
                $query->where('vacate_room_status', 1);
                $query->where('settlement_status', 0);
                $query->whereHas('grid_price', function($query){
                    $query->where('party_b_fee','>', 0);
                });
            }elseif ($type == 25)  {
                //结算-待结算应缴纳(已付甲)-审批中
                $query->where('settlement_status', 2);
                $query->whereHas('grid_price', function($query){
                    $query->where('party_b_fee','>', 0);
                });
            }elseif ($type == 26)  {
                //银行-待支付
                $query->where('settlement_status', 1);
                $query->where('bank_status', 0);
                $query->whereHas('grid_price', function($query){
                    $query->where('type', 1)->where('party_a_fee','>', 0)->where('party_b_fee', 0);
                });
            }elseif ($type == 27)  {
                //银行-待支付-审批中
                $query->where('bank_status', 2);
            }elseif ($type == 28)  {
                //银行-已支付
                $query->where('bank_status', 1);
            }elseif ($type == 29)  {
                //银行-已结算应缴纳(已付甲)
                $query->where('settlement_status', 1);
                $query->whereHas('grid_price', function($query){
                    $query->where('party_b_fee','>', 0);
                });
            }elseif ($type == 30)  {
                //发放-待发放
                $query->where('bank_status', 1);
                $query->where('grant_status', 0);
            }elseif ($type == 31)  {
                //发放-待发放-审批中
                $query->where('grant_status', 2);
            }elseif ($type == 32)  {
                //发放-已发放
                $query->where('grant_status', 1);
            }elseif ($type == 33)  {
                //测绘-待审核
                $query->where('mapping_status', 2);
            }elseif ($type == 34)  {
                //评估-待审核
                $query->where('assess_status', 2);
            }
        })
        ->orderBy('id')
        ->paginate(20);
 
        // 0未开始1进行中2待签约3已签约4已腾房5已结算6已银行7已发放
        foreach($data->items() as &$v){
            $v['list_name']=$v['name'].'-'.implode(',',array_column(json_decode($v['villager'],true),'name'));
            
            $v['now_status']=$v['into_door_status'];

            // 判断是否完成入户，测绘，评估，户型环节
            if($v['into_door_status']==1
               &&($v['mapping_company_id']==0||$v['mapping_status']==1)
               &&($v['assess_company_id']==0||$v['assess_status']==1)
               &&($v['supply_form']==1||$v['house_status']==1)){// 已完成（待签约）
                $v['now_status']=2;
            }elseif($v['into_door_status']==0){//未开始
                $v['now_status']=0;
            }else{//进行中
                $v['now_status']=1;
            }
            
            if($v['sign_status']==1){//已签约
                $v['now_status']=3;
            }
            if($v['vacate_room_status']==1){//已腾房
                $v['now_status']=4;
            }
            if($v['settlement_status']==1){//已结算
                $v['now_status']=5;
            }
            if($v['bank_status']==1){//已银行
                $v['now_status']=6;
            }
            if($v['grant_status']==1){//已发放
                $v['now_status']=7;
            }
        }

        return showData($data);
    }

    // 获取网格数量
    public function gridNum(Request $request){
        $validate = Validator::make($request->all(), [
            'type' => 'required',
        ], [
            'type.required' => '请输入类型',
        ]);

        if ($validate->fails()) {
            return showError($validate->errors()->first());
        }

        $params = $validate->getData();

        $type_arr=[1=>[1,2,3],2=>[4,5,33,-8],3=>[6,7,34,-9],4=>[8,9],5=>[10,11,12,13,14,-1],6=>[15,16,17,-2],7=>[18,19,20,21,22,23,24,25,-3,-4,-5],8=>[26,27,28,29,-6,-7],9=>[30,31,32]];
        $type=$type_arr[$params['type']];
        foreach($type as $v){
            $data[$v]=$this->getNum($v);
        
        }
      
        return showData($data);
    }

    public function getNum($type){
        $user=auth('api')->user()??'';
        $num = Grid::query()
        ->with('approval_list:apply_status,apply_type,grid_id')
        ->where('project_id',$user->project_id??0)
        ->where('segment_id',$user->segment_id??0)
        ->whereIn('grid_group_id',explode(',',$user->grid_group_id))
        ->where('opinion','<>',2)
        ->when($type, function ($query) use ($type) {
            if ($type == 1) {
                //入户-未开始
                $query->where('into_door_status', 0);
            } elseif ($type == 2) {
                //入户-进行中
                $query->where('into_door_status', 2);
            } elseif ($type == 3)  {
                //入户-已完成
                $query->where('into_door_status', 1);
            }elseif ($type == 4)  {
                //测绘-待测绘
                $query->where('mapping_company_id','<>', 0);
                $query->where('mapping_status', 0);
            }elseif ($type == 5)  {
                //测绘-已测绘
                $query->where('mapping_status', 1);
            }elseif ($type == 6)  {
                //评估-待评估
                $query->where('assess_company_id','<>', 0);
                $query->where('assess_status', 0);
            }elseif ($type == 7)  {
                //评估-已评估
                $query->where('assess_status', 1);
            }elseif ($type == 8)  {
                //户型-待选择
                $query->where('into_door_status', 1);
                $query->where('supply_form', 2);
                $query->where('house_status', 0);
                $query->whereHas('approval_list', function($query){
                    $query->whereIn('apply_type', [14,15,17,18])->where('apply_status', 1);
                });
            }elseif ($type == 9)  {
                //户型-已选择
                $query->where('house_status', 1);
            }elseif ($type == 10)  {
                //签约-待签约
                $query->where('into_door_status', 1);
                $query->where('sign_status', 0);
                $query->whereHas('approval_list', function($query){
                    $query->whereIn('apply_type', [14,15,17,18])->where('apply_status', 1);
                });
                $query->where(function($query) {
                    $query->where('dualuse_area', 0)
                    ->orWhere(function($query){
                        $query->whereHas('approval_list', function($query) {
                            $query->where('apply_type', 16)->where('apply_status', 1);
                        });
                    });
                });
            }elseif ($type == 11)  {
                //签约-待签约-审批中
                $query->where('sign_status', 2);
            }elseif ($type == 12)  {
                //签约-已签约
                $query->where('sign_status', 1);
            }elseif ($type == 13)  {
                //签约-已签约-应支付(甲付已)
                $query->where('sign_status', 1);
                $query->whereHas('grid_price', function($query){
                    $query->where('party_a_fee','>=', 0)->where('party_b_fee', 0);
                });
            }elseif ($type == 14)  {
                //签约-已签约-应缴纳(已付甲)
                $query->where('sign_status', 1);
                $query->whereHas('grid_price', function($query){
                    $query->where('party_b_fee','>', 0);
                });
            }elseif ($type == 15)  {
                //腾房-待腾房
                $query->where('sign_status', 1);
                $query->where('if_sign', 1);
                $query->where('vacate_room_status', 0);
            }elseif ($type == 16)  {
                //腾房-待腾房-审批中
                $query->where('vacate_room_status', 2);
            }elseif ($type == 17)  {
                //腾房-已腾房
                $query->where('vacate_room_status', 1);
            }elseif ($type == 18)  {
                //结算-已签约并腾房-应支付(甲付已)
                $query->where('sign_status', 1);
                $query->where('if_sign', 1);
                $query->where('vacate_room_status', 1);
                $query->whereHas('grid_price', function($query){
                    $query->where('party_a_fee','>=', 0)->where('party_b_fee', 0);
                });
            }elseif ($type == 19)  {
                //结算-已签约并腾房-应缴纳(已付甲)
                $query->where('sign_status', 1);
                $query->where('if_sign', 1);
                $query->where('vacate_room_status', 1);
                $query->whereHas('grid_price', function($query){
                    $query->where('party_b_fee','>', 0);
                });
            }elseif ($type == 20)  {
                //结算-已结算应支付(甲付已)
                $query->where('settlement_status', 1);
                $query->whereHas('grid_price', function($query){
                    $query->where('party_a_fee','>=', 0)->where('party_b_fee', 0);
                });
            }elseif ($type == 21)  {
                //结算-待结算应支付(甲付已)
                $query->where('vacate_room_status', 1);
                $query->where('settlement_status', 0);
                $query->whereHas('grid_price', function($query){
                    $query->where('party_a_fee','>=', 0)->where('party_b_fee', 0);
                });
            }elseif ($type == 22)  {
                //结算-待结算应支付(甲付已)-审批中
                $query->where('settlement_status', 2);
                $query->whereHas('grid_price', function($query){
                    $query->where('party_a_fee','>=', 0)->where('party_b_fee', 0);
                });
            }elseif ($type == 23)  {
                //结算-已结算应缴纳(已付甲)
                $query->where('settlement_status', 1);
                $query->whereHas('grid_price', function($query){
                    $query->where('party_b_fee','>', 0);
                });
            }elseif ($type == 24)  {
                //结算-待结算应缴纳(已付甲)
                $query->where('vacate_room_status', 1);
                $query->where('settlement_status', 0);
                $query->whereHas('grid_price', function($query){
                    $query->where('party_b_fee','>', 0);
                });
            }elseif ($type == 25)  {
                //结算-待结算应缴纳(已付甲)-审批中
                $query->where('settlement_status', 2);
                $query->whereHas('grid_price', function($query){
                    $query->where('party_b_fee','>', 0);
                });
            }elseif ($type == 26)  {
                //银行-待支付
                $query->where('settlement_status', 1);
                $query->where('bank_status', 0);
                $query->whereHas('grid_price', function($query){
                    $query->where('type', 1)->where('party_a_fee','>', 0)->where('party_b_fee', 0);
                });
            }elseif ($type == 27)  {
                //银行-待支付-审批中
                $query->where('bank_status', 2);
            }elseif ($type == 28)  {
                //银行-已支付
                $query->where('bank_status', 1);
            }elseif ($type == 29)  {
                //银行-已结算应缴纳(已付甲)
                $query->where('settlement_status', 1);
                $query->whereHas('grid_price', function($query){
                    $query->where('party_b_fee','>', 0);
                });
            }elseif ($type == 30)  {
                //发放-待发放
                $query->where('bank_status', 1);
                $query->where('grant_status', 0);
            }elseif ($type == 31)  {
                //发放-待发放-审批中
                $query->where('grant_status', 2);
            }elseif ($type == 32)  {
                //发放-已发放
                $query->where('grant_status', 1);
            }elseif ($type == -1)  {
                //签约-待签约-总计
                $query->where('into_door_status', 1);
                $query->where('sign_status', '<>',1);
                $query->whereHas('approval_list', function($query){
                    $query->whereIn('apply_type', [14,15,17,18])->where('apply_status', 1);
                });
                $query->where(function($query) {
                    $query->where('dualuse_area', 0)
                    ->orWhere(function($query){
                        $query->whereHas('approval_list', function($query) {
                            $query->where('apply_type', 16)->where('apply_status', 1);
                        });
                    });
                });
            }elseif ($type == -2)  {
                //腾房-待腾房-总计
                $query->where('sign_status', 1);
                $query->where('if_sign', 1);
                $query->where('vacate_room_status', '<>',1);
            }elseif ($type == -3)  {
                //结算-已签约并腾房-总计
                $query->where('sign_status', 1);
                $query->where('if_sign', 1);
                $query->where('vacate_room_status', 1);
            }elseif ($type == -4)  {
                //结算-待结算应支付(甲付已)-总计
                $query->where('vacate_room_status', 1);
                $query->where('settlement_status', '<>',1);
                $query->whereHas('grid_price', function($query){
                    $query->where('party_a_fee','>=', 0)->where('party_b_fee', 0);
                });
            }elseif ($type == -5)  {
                //结算-待结算应缴纳(已付甲)-总计
                $query->where('vacate_room_status', 1);
                $query->where('settlement_status', '<>',1);
                $query->whereHas('grid_price', function($query){
                    $query->where('party_b_fee','>', 0);
                });
            }elseif ($type == -6)  {
                //银行-结算总户数-总计
                $query->where('settlement_status', 1);
            }elseif ($type == -7)  {
                //银行-待支付-总计
                $query->where('settlement_status', 1);
                $query->where('bank_status','<>' ,1);
                $query->whereHas('grid_price', function($query){
                    $query->where('type', 1)->where('party_a_fee','>', 0)->where('party_b_fee', 0);
                });
            }elseif ($type == -8)  {
                //测绘-待测绘-总计
                $query->where('mapping_company_id','<>', 0);
                $query->where('mapping_status', '<>' ,1);
            }elseif ($type == -9)  {
                //评估-待评估-总计
                $query->where('assess_company_id','<>', 0);
                $query->where('assess_status','<>' ,1);
            }elseif ($type == 33)  {
                //测绘-待审核
                $query->where('mapping_status', 2);
            }elseif ($type == 34)  {
                //评估-待审核
                $query->where('assess_status', 2);
            }
        })
        ->count();
        return $num;
    }

    // 签约结算银行发放首页获取金额
    public function gridPrice(Request $request){
        $validate = Validator::make($request->all(), [
            'type' => 'required|in:0,1,2,3',
        ], [
            'type.required' => '请输入类型',
            'type.in' => '请输入正确的类型',
        ]);

        if ($validate->fails()) {
            return showError($validate->errors()->first());
        }

        $params = $validate->getData();

        $project_id=auth('api')->user()->project_id??2;

        if($params['type']==0){
            // 已签约甲付已金额
            $party_a_fee = GridPrice::query()
            ->where('project_id',$project_id)
            ->where('type',0)
            ->whereHas('grid', function($query) {
                $query->where('sign_status',1);
            })
            ->sum('party_a_fee');

            // 已签约已付甲金额
            $party_b_fee = GridPrice::query()
            ->where('project_id',$project_id)
            ->where('type',0)
            ->whereHas('grid', function($query) {
                $query->where('sign_status',1);
            })
            ->sum('party_b_fee');

            $data=[
                'party_a_fee'=>round($party_a_fee,2),
                'party_b_fee'=>round($party_b_fee,2),
             ];
        }else{
        // 总
            $total_status=[1=>'vacate_room_status',2=>'settlement_status',3=>'bank_status'];
            //甲付已
            $total_type_a=[1=>'party_a_fee',2=>'party_a_fee',3=>'pay_fee'];
            $total_money_a = GridPrice::query()
            ->where('project_id',$project_id)
            ->where('type',$params['type']-1)
            ->whereHas('grid', function($query) use ($total_status,$params){
                $query->where($total_status[$params['type']], 1);
            })
            ->sum($total_type_a[$params['type']]);
            //已付甲
            // $total_type_b=[1=>'party_b_fee',2=>'party_b_fee',3=>'pay_fee'];
            $total_money_b = GridPrice::query()
            ->where('project_id',$project_id)
            ->where('type',$params['type']-1)
            ->whereHas('grid', function($query) use ($total_status,$params){
                $query->where($total_status[$params['type']], 1);
            })
            ->sum('party_b_fee');
        // 已
            //甲付已
            $yes_status_a=[1=>'settlement_status',2=>'bank_status',3=>'grant_status'];
            $yes_type_a=[1=>'party_a_fee',2=>'pay_fee',3=>'pay_fee'];
            $yes_money_a = GridPrice::query()
            ->where('project_id',$project_id)
            ->where('type',$params['type'])
            ->whereHas('grid', function($query) use ($yes_status_a,$params){
                $query->where($yes_status_a[$params['type']], 1);
            })
            ->sum($yes_type_a[$params['type']]);
            //已付甲
            // $yes_status_b=[1=>'settlement_status',2=>'settlement_status',3=>'grant_status'];
            // $yes_type_b=[1=>'party_b_fee',2=>'party_b_fee',3=>'pay_fee'];
            $yes_money_b = GridPrice::query()
            ->where('project_id',$project_id)
            ->where('type',1)
            ->whereHas('grid', function($query) {
                $query->where('settlement_status', 1);
            })
            ->sum('party_b_fee');
        // 未
            $not_money_a=$total_money_a -$yes_money_a;//甲付已
            $not_money_b=$total_money_b -$yes_money_b;//已付甲

            $data=[
                'total_money_a'=>round($total_money_a,2),
                'yes_money_a'=>round($yes_money_a,2),
                'not_money_a'=>round($not_money_a,2),
                'total_money_b'=>round($total_money_b,2),
                'yes_money_b'=>round($yes_money_b,2),
                'not_money_b'=>round($not_money_b,2),
             ];
        }

        return showData($data);
    }

    // 银行总金额页面获取金额
    public function gridPriceDetails(Request $request){
        $sum_type=['subsidy_fee','transition_fee','require_sign_fee','require_clear_fee',
        'if_decorate_fee','house_difference_fee','house_difference_fee_a','house_difference_fee_b','stop_fee','lack_area_fee','money_fee',
        'yard_fee','othe_build_fee','use_fee','assess_fee','other_subsidy_fee','subsidiary_fee'];

        $party_a_fee=$this -> getPriceDetails('party_a_fee');
        $party_b_fee=$this -> getPriceDetails('party_b_fee');

        $data=[];
        $mark='';
        foreach($sum_type as $k=> $v){
            $name=$v;
            if($v=="house_difference_fee_a"){
                $mark='>';
                $v='house_difference_fee';
            }
            if($v=="house_difference_fee_b"){
                $mark='<';
                $v='house_difference_fee';
            }
            $li['num']=$this -> getPriceDetails($v,$mark);
            $li['scale']=round($li['num']/($party_a_fee-$party_b_fee)*100,2);
            $data[$name]=$li;
            $mark='';
        }
        $data['party_a_fee']=['num'=>$party_a_fee,'scale'=>100];
        $data['party_b_fee']=['num'=>'-'.$party_b_fee,'scale'=>0];

        return showData($data);
    }

    public function getPriceDetails($type,$mark=''){
        $project_id=auth('api')->user()->project_id??2;

        $num = GridPrice::query()
        ->where('project_id',$project_id)
        ->where('type',1)
        ->when($mark, function ($query) use ($type,$mark) {
            $query->where($type,$mark,0);
        })
        ->sum($type);

        return round($num,2);
    }

    // 获取协议配置信息
    public function protocolSetList(Request $request)
    {
        $validate = Validator::make($request->all(), [
            'grid_id' => 'required',
            'supply_form' => 'required',
            'build_form' => 'required',
        ], [
            'grid_id.required' => '请输入网格id',
            'supply_form.required' => '请输入补偿方式',
            'build_form.required' => '请输入建筑形式',
        ]);

        if ($validate->fails()) {
            return showError($validate->errors()->first());
        }

        $params = $validate->getData();

        $grid=Grid::query()->where('id',$params['grid_id'])->first();
        if(!$grid){
            return showError('网格不存在');
        }

        $data=ProtocolSet::query()
        ->where('supply_form',$params['supply_form'])
        ->where('build_form',$params['build_form'])
        ->where('street_id',$grid['street_id'])
        ->where('village_id',$grid['village_id'])
        ->where('project_id',$grid['project_id'])
        ->where('segment_id',$grid['segment_id'])
        ->first();

        if(!$data){
            return showError('未查询到配置信息，请联系管理员到后台配置');
        }

        return showData($data);
    }

    // 根据网格id获取网格、村民、代理人信息
    public function gridInfoList(Request $request)
    {
        $validate = Validator::make($request->all(), [
            'grid_id' => 'required',
        ], [
            'grid_id.required' => '请输入网格id',
        ]);

        if ($validate->fails()) {
            return showError($validate->errors()->first());
        }

        $params = $validate->getData();

        $data=Grid::query()
        ->where('id',$params['grid_id'])
        ->with('villager:name,identity_card,phone,grid_id')
        ->with('agent:name,identity_card,phone,grid_id')
        ->first()
        ->toArray();

        return showData($data);
    }

    // 评估项目类别
    public function AssessType(Request $request)
    {
        $name = $request->input('name', '');
        $id = $request->input('id', '');

        $data=AssessType::query()
        ->when($name, function ($query) use ($name) {
            $query->where('name', 'like', "%{$name}%");
        })
        ->when($id, function ($query) use ($id) {
            $query->where('id', $id);
        })
        ->where('pid','<>',0)
        ->get()
        ->toArray();

        if($id){
            $data=$data[0];
            $data['pid_name']=AssessType::query()->where('id',$data['pid'])->value('name');
        }

        return showData($data);
    }
}

